<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Inventory\Timely;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductMixSku;
use App\Models\Product\ProductPackageMaterial;
use App\Models\Product\ProductPpt;
use App\Models\Product\ProductQuality;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;
class SkuListController extends AdminController{

    protected $title = '产品列表';

    protected function grid()
    {
        \Encore\Admin\Admin::style($this->_style());
        $grid = new Grid(new ProductSku());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->instant = Timely::getInstant($item->id);
                if($item->is_mix == 1){
                    $re = ProductMixSku::getMixSkuPuCycleAndPuPriceAndNoTax($item->mix_rule);
                    $item->supplier_price = numberFormat($re['supplier_price']);
                    $item->unit_price = numberFormat($re['unit_price']);
                    $item->self_price = numberFormat(round($re['unit_price'] - $re['supplier_price'],3));
                    $item->unit_price_no_tax = numberFormat($re['unit_price_no_tax']);
                    $item->purchase_cycle = numberFormat($re['purchase_cycle']);
                    $item->transit = 0;
                }else{
                    $item->transit = Timely::getTransit($item->id);
                    $supplierPrice = $item->product_supplier->supplier_price ?? 0;
                    $unitPrice = $item->product_supplier->unit_price ?? 0;
                    $item->supplier_price = numberFormat($supplierPrice);
                    $item->unit_price = numberFormat($unitPrice);
                    $item->self_price = numberFormat(round($unitPrice - $supplierPrice,3));
                    $item->unit_price_no_tax = numberFormat(ProductSku::tax($unitPrice,$item->product_supplier->supplier->tax ?? 0));
                    $item->purchase_cycle = numberFormat($item->product_supplier->purchase_cycle ?? 0);
                }
                $item->muser_id = User::getUsernameById($item->muser_id);
                $item->cuser_id = User::getUsernameById($item->cuser_id);
            }
            return $collection;
        });
        $grid->column('id','ID');
        $grid->column('psku_code','SKU');
        $grid->column('part_number','PartNo.');
        $grid->column('is_sales','是否在售')->bool();
        $grid->column('is_mix','组合')->using(ProductSku::$_isMix);
        $grid->column('mix_rule','组合规则');
        $grid->column('psku_cn','名称');
        $grid->column('classify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('classify.title','品类');
        $grid->column('classify.model_no','ModelNo');
        $grid->column('img','图片')->display(function ($value){
            return ProductSku::getMainImage($value,60,60);
        });
        $grid->column('supplier_price','供应商单价');
        $grid->column('self_price','自购单价');
        $grid->column('unit_price','总采购单价');
        $grid->column('unit_price_no_tax','不含税总单价');
        $grid->column('purchase_cycle','采购周期');
        $grid->column('instant','库存');
        $grid->column('transit','在途');
        $grid->column('psku_status','产品状态')->using(ProductSku::$_pSkuStatus);
        $grid->column('muser_id','负责人');
        $grid->column('cuser_id','创建人');
        $grid->column('status','是否启用')->bool([1 => true, 2 => false]);
        $grid->column('is_brand','是否为品牌产品')->bool([ProductSku::BRAND_YES => true, ProductSku::BRAND_NO => false]);

        $grid->fixHeader();
        $grid->fixColumns(0, -3);
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/sku-list-download'));
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableEdit();
        });
        $grid->disableBatchActions();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter){
                $filter->disableIdFilter(false);
                $filter->where(function ($query) {
                    $query->where('psku_code', 'like', "%{$this->input}%")
                        ->orWhere('psku_cn', 'like', "%{$this->input}%")
                        ->orWhere('part_number', 'like', "%{$this->input}%");
                }, '查询','sku8')->placeholder('模糊查询SKU，名称，PartNo.');
                $filter->equal('classify.season', '季节性')->select(ProductClassify::$_season);
            });
            $filter->column(1/3, function ($filter) {
                $filter->in('psku_status', '状态')->checkbox(ProductSku::$_pSkuStatus);
                $filter->in('is_mix', '组合')->checkbox(ProductSku::$_isMix);
                $filter->equal('classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->in('status', '启用')->checkbox(ProductSku::$_status);
                $filter->in('is_sales','在售')->checkbox(ProductSku::$_isSales);
                $filter->equal('muser_id','负责人')->select(User::getMUserOptions(FALSE));
//                $filter->equal('cuser_id','创建人')->select(User::getCUserOptions());
            });
        });

        return $grid;
    }

    protected function detail($id)
    {
        $ps = ProductSku::query()->findOrFail($id);
        $ppt = ProductPpt::query()->where('classify_id',$ps->classify_id)->value('ppt');
        $qualities = ProductQuality::query()->where('classify_id',$ps->classify_id)->value('qualities');
        $packages = ProductPackageMaterial::query()->where('classify_id',$ps->classify_id)->value('packages');
        if($ps->is_mix == 1){
            $re = ProductMixSku::getMixSkuPuCycleAndPuPriceAndNoTax($ps->mix_rule);
            $unitPrice = numberFormat($re['unit_price']);
            $unitPriceNoTax = numberFormat($re['unit_price_no_tax']);
            $purchaseCycle = numberFormat($re['purchase_cycle']);
        }else{
            $unitPrice = numberFormat($ps->product_supplier->unit_price ?? 0);
            $unitPriceNoTax = numberFormat(ProductSku::tax($ps->product_supplier->unit_price ?? 0,$ps->product_supplier->supplier->tax ?? 0));
            $purchaseCycle = numberFormat($ps->product_supplier->purchase_cycle ?? 0);
        }
        return view('products.sku-list.detail.index', compact('id','ps','unitPrice','unitPriceNoTax','purchaseCycle','ppt','qualities','packages'));
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->where(function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%")
                        ->orWhere('part_number', 'like', "%{$_filter}%");
                });
            }
            if($key == 'classify'){
                $query->whereHas('classify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['is_mix','psku_status','status','is_sales'])){
                $query->whereIn($key,$_filter);
            }
            if(in_array($key,['muser_id','classify_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['SKUID','SKU','PartNo.','组合','组合规则','是否在售','名称','季节性','品类','Model No','供应商单价','自购单价','总采购单价','不含税总单价','采购周期','库存','在途','产品状态','负责人','创建人','创建时间','状态','是否为品牌产品','描述','图片链接'];
        RExcel::exportCsv('产品列表',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            if(!array_key_exists($model->muser_id,$seller)){
                $seller[$model->muser_id] = User::getUsernameById($model->muser_id);
            }
            if(!array_key_exists($model->cuser_id,$seller)){
                $seller[$model->cuser_id] = User::getUsernameById($model->cuser_id);
            }
            if($model->is_mix == 1){
                $data = ProductMixSku::getMixSkuPuCycleAndPuPriceAndNoTax($model->mix_rule);
                $supplierPrice = numberFormat($data['supplier_price']);
                $unitPrice = numberFormat($data['unit_price']);
                $selfPrice = numberFormat(round($data['unit_price'] - $data['supplier_price'],3));
                $unitPriceNoTax = numberFormat($data['unit_price_no_tax']);
                $purchaseCycle = numberFormat($data['purchase_cycle']);
                $transit = 0;
            }else{
                $transit = Timely::getTransit($model->id);
                $supplierPrice = $model->product_supplier->supplier_price ?? 0;
                $unitPrice = $model->product_supplier->unit_price ?? 0;
                $selfPrice = round($unitPrice - $supplierPrice,3);
                $unitPriceNoTax = numberFormat(ProductSku::tax($unitPrice,$model->product_supplier->supplier->tax ?? 0));
                $purchaseCycle = numberFormat($model->product_supplier->purchase_cycle ?? 0);
            }
            $temp = [
                $model->id,
                $model->psku_code,
                $model->part_number,
                ProductSku::$_isMix[$model->is_mix],
                $model->mix_rule,
                ProductSku::$_isSales[$model->is_sales],
                $model->psku_cn,
                ProductClassify::$_season[$model->classify->season ?? 3],
                $model->classify->title ?? '',
                $model->classify->model_no ?? '',
                numberFormat($supplierPrice),
                numberFormat($selfPrice),
                numberFormat($unitPrice),
                $unitPriceNoTax,
                $purchaseCycle,
                Timely::getInstant($model->id),
                $transit,
                ProductSku::$_pSkuStatus[$model->psku_status],
                $seller[$model->muser_id],
                $seller[$model->cuser_id],
                $model->created_at,
                ProductSku::$_status[$model->status],
                ProductSku::$_brand[$model->is_brand],
                $model->psku_describe,
                ProductSku::getMainImageSrc($model->img),
            ];
            yield $temp;
        }
    }

    protected function _style()
    {
        return <<<STYLE
    .table > thead > tr > th, .table > tbody > tr > td {
        white-space: nowrap;
    }
    .table-responsive {
        max-height: calc(80vh);
    }
STYLE;
    }

}
